import axios from "axios";
import NProgress from "nprogress";
import { Message } from 'element-ui';
import { clearCookie, clearStore, getCookie } from "xingyuelongchen";
const cancelToken = axios.CancelToken;
let axiosRequestList = [];
let messageNotice = null;
NProgress.configure({
  easing: "ease",
  speed: 500,
  showSpinner: true
});
const errorMessage = { 400: '请求错误', 401: '暂无权限', 404: '资源不存在', 500: '服务器错误' }

const removePending = (config) => {
  NProgress.done();
  for (let i in axiosRequestList) {
    if (axiosRequestList[i].url === axios.defaults.baseURL + config.url) {
      axiosRequestList[i].cancel();
      axiosRequestList.splice(i, 1);
    }
  }
}
export const saveFile = (res, filename = '') => {
  let blob = new Blob([res.data], { type: res.config.responseType || res.response['content-type'] || 'blob' });
  let fileName = filename || res.headers['content-disposition'].replace(/^.*filename=/g, '');
  fileName = decodeURIComponent(fileName);
  if (window.navigator.msSaveOrOpenBlob) {
    navigator.msSaveBlob(blob, fileName);
    return;
  }
  let downloadElement = document.createElement('a');
  let href = window.URL.createObjectURL(blob);
  downloadElement.href = href;
  downloadElement.download = fileName.length ? decodeURIComponent(fileName[0]) : '未命名';
  document.body.appendChild(downloadElement);
  downloadElement.click();
  document.body.removeChild(downloadElement);
  window.URL.revokeObjectURL(href);
}
const request = (config) => {
  removePending(config);
  if (!config.removePending) config.cancelToken = new cancelToken(function executor(c) {
    axiosRequestList.push({
      url: axios.defaults.baseURL + config.url,
      cancel: c
    });
  });
  NProgress.start();
  if (getCookie('token')) config.headers["token"] = getCookie('token');
  return config;
}
const requestError = (err) => {
  let { config = {} } = err;
  removePending(config);
  return Promise.reject(err);
}
const response = (res) => {
  let { data, config, status, statusText } = res;
  removePending(config);
  if (status === 200) {
    if (['blob', 'arraybuffer'].includes(config.responseType)) { saveFile(res); return res }
    if (data.code == 401) {
      clearStore();
      clearCookie();
      if (process.env.NODE_ENV != 'development') window.location.href = process.env.VUE_APP_PUBLIC_PATH + '/';
      else window.location.href = '/';
      return
    }
    if (data.message || data.msg) {
      messageNotice && messageNotice.close();
      if (data.code && data.code == 200) messageNotice = Message.success(data.message || data.msg);
      else messageNotice = Message.error(data.message || data.msg);
    }
    if (data.code == 200) return res;
  }
  return Promise.reject(res);
}
const responseError = (err) => {
  let { config = {}, response = null } = err;
  removePending(config);
  if (response && response.status) {
    messageNotice && messageNotice.close();
    messageNotice = Message.error(errorMessage[response.status] || response.statusText);
  }
  return Promise.reject(err);
}
axios.defaults["baseURL"] = process.env.VUE_APP_BASE_API || '';
axios.defaults["timeout"] = process.env.VUE_APP_TIMEOUT || 10000;
axios.defaults["crossDomain"] = true;
axios.defaults["withCredentials"] = true;
axios.defaults["method"] = "get";
axios.defaults.headers.common["Accept-Language"] = "zh-cn";
axios.interceptors.request.use(request, requestError);
axios.interceptors.response.use(response, responseError);

export default axios


